import type {
  IPagination,
  IPostTemplate,
  IPostTemplateStatistics,
} from '@/interfaces';
import type { TBody, TParams } from '@/types';
import { createConfig, getQueryParams, handleReqMiddleware } from '@/lib/api';

export const createPostTemplate = (
  params: TBody<{
    name: string;
    content: string;
    sectionId: number;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'POST' });
  return fetch(config.baseURL + '/forum/templates', config).then(
    handleReqMiddleware
  );
};

export const updatePostTemplate = (
  params: TBody<{
    name?: string;
    overview?: string;
    content?: string;
    sort?: number;
    sectionId?: number;
  }>
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'PUT' });
  return fetch(config.baseURL + `/forum/templates/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const removePostTemplate = (
  params: TBody<void>
): Promise<Response | boolean> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(config.baseURL + `/forum/templates/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const queryPostTemplateStatistics = (
  params?: TParams
): Promise<Response | IPostTemplateStatistics> => {
  const config = createConfig(params);
  return fetch(config.baseURL + '/forum/templates/statistics', config).then(
    handleReqMiddleware
  );
};

export const queryAllPostTemplate = (
  params?: TParams
): Promise<Response | IPagination<IPostTemplate>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/templates?${getQueryParams(config)}`,
    config
  ).then(handleReqMiddleware);
};

export const queryPostTemplate = (
  params?: TParams
): Promise<Response | IPostTemplate> => {
  const config = createConfig(params);
  return fetch(config.baseURL + `/forum/templates/${config.id}`, config).then(
    handleReqMiddleware
  );
};

export const queryPostTemplateBySection = (
  params?: TParams
): Promise<Response | IPostTemplate[]> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/forum/templates/sections/${config.id}`,
    config
  ).then(handleReqMiddleware);
};
